package cn.fanyamin.action;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.fanyamin.model.Book;
import cn.fanyamin.model.Category;
import cn.fanyamin.service.BookDaoService;
import cn.fanyamin.service.BookService;
import cn.fanyamin.service.CategoryDaoService;
import cn.fanyamin.service.CategoryService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.Validateable;

public class BookAction extends ActionSupport implements ModelDriven<Book>,
        Preparable, Validateable {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 6523451135915387939L;

    private static Log logger = LogFactory.getLog(BookAction.class);

    private static BookService bookService = new BookDaoService();

    private static CategoryService categoryService = new CategoryDaoService();

    private Book book;

    private List<Book> books;

    private List<Category> categories;

    public Book getModel() {
    	 logger.info("getModel " + this.book);
        return this.book;
    }

    public void prepare() throws Exception {
        categories = categoryService.getAllCategories();
        logger.info("prepare " + categories);
        if (book != null && book.getBookId() != null) {
            book = bookService.getBook(book.getBookId());
        }
    }

    public String doSave() {
        if (book.getBookId() == null) {
            bookService.insertBook(book);
        } else {
            bookService.updateBook(book);
        }
        return SUCCESS;
    }

    public String doDelete() {
        bookService.deleteBook(book.getBookId());
        return SUCCESS;
    }

    public String doList() {
        books = bookService.getAllBooks();
        return SUCCESS;
    }

    public String doInput() {
        return INPUT;
    }

    /**
     * @return Returns the book.
     */
    public Book getBook() {
        return book;
    }

    /**
     * @param book
     *            The book to set.
     */
    public void setBook(Book book) {
        this.book = book;
    }

    /**
     * @return Returns the books.
     */
    public List<Book> getBooks() {
        return books;
    }

    /**
     * @return Returns the categories.
     */
    public List<Category> getCategories() {
        return categories;
    }
    
    public void validate() {
        if(this.book == null) {
            //go to input page
            return;
        }
        if(StringUtils.isBlank(this.book.getBookName())) {
            addFieldError("book.bookName" , "Book name is empty.");
        }
    }
}
